package com.dell.xiaodaiyu.demo.service.iml;

import com.dell.xiaodaiyu.demo.service.WeatherService;
import com.dell.xiaodaiyu.demo.vo.WeatherRespon;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Service
public class WeatherServiceImpl implements WeatherService {

    private final static String WEATHE_URL = "http://wthrcdn.etouch.cn/weather_mini?";

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public WeatherRespon getWeatherByCityId(String cityId) {
        String url = WEATHE_URL+"citykey="+cityId;
        return this.getResponByUrl(url);
    }

    @Override
    public WeatherRespon getWeatherByCityName(String cityName) {
        String url = WEATHE_URL+"city="+cityName;
        return this.getResponByUrl(url);
    }

    private WeatherRespon getResponByUrl(String url){
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
        ObjectMapper objectMapper = new ObjectMapper();
        WeatherRespon weatherRespon = null;
        if (responseEntity.getStatusCodeValue()==200){
            try {
                weatherRespon = objectMapper.readValue(responseEntity.getBody(),WeatherRespon.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return weatherRespon;
    }
}
